package com.yedean.factory.strategy;

import com.yedean.factory.BeansException;
import com.yedean.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Objects;

/**
 * JDKInstantiationStrategy  实例化对象
 *
 * @author yedean
 * @date 2022/6/30
 */
public class JDKInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(BeanDefinition definition, String beanName, Constructor<?> ctor, Object[] args) {
        Class<?> beanClass = definition.getBeanClass();

        try {
            //判断ctor构造器是否有  有的话走构造器创建实例 没有的话直接创建实例
            if (Objects.nonNull(ctor)) {
                return beanClass.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
            } else {
                return beanClass.newInstance();
            }
        } catch (NoSuchMethodException | InvocationTargetException | InstantiationException |
                 IllegalAccessException e) {
            throw new BeansException("bean实例化失败," + e);
        }

    }
}
